package com.ubtechinc.cruzr.launcher2.model.helper;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.ubtechinc.cruzr.launcher2.utlis.LogUtils;
import com.ubtechinc.cruzr.sdk.status.SystemStatus;
import com.ubtechinc.cruzr.sdk.status.SystemStatusApi;
import com.ubtechinc.cruzr.serverlibutil.aidl.State;
import com.ubtechinc.cruzr.serverlibutil.aidl.StateRule;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

public class ThirdStateHelper {
    public static final int THIRD_APP_STATUS = 1000;
    private static final int DISPLAY_TASKS = 20;
    private static final int MAX_TASKS = DISPLAY_TASKS + 1; // allow extra for
    private static final String RECORD_AUDIO = "android.permission.RECORD_AUDIO";
    private static final String  CAMERA = "android.permission.CAMERA";
    private static int [] interrupt = new int[]{SystemStatus.STATUS_AUTO_SERVICE,SystemStatus.STATUS_EXTRA2,SystemStatus.STATUS_STANDBY,SystemStatus.STATUS_FREE_GUIDE
            ,SystemStatus.STATUS_CHAT, SystemStatus.STATUS_VIDEO_PLAYING,SystemStatus.STATUS_MUSIC_PLAYING,SystemStatus.STATUS_INTRODUCE_SELF,SystemStatus.STATUS_FACE_RECO
            ,104,105,SystemStatus.STATUS_COMMON_APK};

    private static int [] interrupted = new int[]{SystemStatus.STATUS_REMOTE_CONTORL,SystemStatus.STATUS_SYSTEM_UPDATE,SystemStatus.STATUS_EMERGENCY,SystemStatus.STATUS_VIDEO_CALL,SystemStatus.STATUS_AUTO_SERVICE
            ,SystemStatus.STATUS_EXTRA2,  SystemStatus.STATUS_FREE_GUIDE, SystemStatus.STATUS_VIDEO_PLAYING,SystemStatus.STATUS_MUSIC_PLAYING,SystemStatus.STATUS_ACTION,
            SystemStatus.STATUS_CHARGE};


    public static void  setThirdAppState(){
        /**chatCommand(true).chatCommandNoisy(true).**/
        State state = new State.StateBuilder(THIRD_APP_STATUS,"education").click(true).sysTips(true).autoRechage(true).autoShutdown(true).emgeStop(true)
                .eletSkin(true).remoteCrl(true).physicalEmgeStop(true).forceOta(true).createState();
        StateRule stateRule = new StateRule(interrupt, interrupted);
        int ret = SystemStatusApi.get().addAppState(state,stateRule);
        LogUtils.e("rqh setThirdAppState  ret = " + ret);
    }
    @SuppressLint("CheckResult")
    @SuppressWarnings("deprecation")
    public static void removeThirdAppTask(final Context context) {
        final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        Observable.create(new ObservableOnSubscribe<List<ActivityManager.RecentTaskInfo>>() {
            @Override
            public void subscribe(ObservableEmitter<List<ActivityManager.RecentTaskInfo>> e) throws Exception {
                final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                final List<ActivityManager.RecentTaskInfo> recentTasks = am.getRecentTasks(MAX_TASKS,
                        ActivityManager.RECENT_IGNORE_UNAVAILABLE | ActivityManager.RECENT_INCLUDE_PROFILES);
                e.onNext(recentTasks);
            }
        }).flatMap(new Function<List<ActivityManager.RecentTaskInfo>, ObservableSource<ActivityManager.RecentTaskInfo>>() {
            @Override
            public ObservableSource<ActivityManager.RecentTaskInfo> apply(List<ActivityManager.RecentTaskInfo> recentTaskInfos) throws Exception {
                return Observable.fromIterable(recentTaskInfos);
            }
        }).filter(new Predicate<ActivityManager.RecentTaskInfo>() {
            @Override
            public boolean test(ActivityManager.RecentTaskInfo recentInfo) throws Exception {
                Intent intent = new Intent(recentInfo.baseIntent);
                String packagename = intent.getComponent().getPackageName();
               // return getUsesPermission(context, packagename) && (!LoadHelper.isSystemApp(context, packagename));
                return !LoadHelper.isSystemApp(context, packagename);
            }
        }).subscribeOn(Schedulers.io()).subscribe(new Consumer<ActivityManager.RecentTaskInfo>() {
            @Override
            public void accept(ActivityManager.RecentTaskInfo recentInfo) throws Exception {
                LogUtils.e("rqh 删除的名是  = " + recentInfo);
                am.removeTask(recentInfo.persistentId);
            }
        });
    }
    public static boolean getUsesPermission(Context context, String packageName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
            String[] usesPermissionsArray = packageInfo.requestedPermissions;
            for (int i = 0; i < usesPermissionsArray.length; i++) {
                //得到每个权限的名字,如:android.permission.INTERNET
                String usesPermissionName = usesPermissionsArray[i];
                if (RECORD_AUDIO.equals(usesPermissionName) || CAMERA.equals(usesPermissionName)) {
                    LogUtils.e("usesPermissionName=" + usesPermissionName);
                    return true;
                }
            }

        } catch (Exception e) {
            LogUtils.e("解析权限出错" );
        }
        return false;
    }
}
